﻿namespace TuneMultiCheckBox.Plugins.Common.TuneMultiCheckBox
{
  using BusinessLogic;
  using Logic.TuneMultiCheckBox;
  using Microsoft.Xrm.Sdk;

  public class SaveCheckboxSet : PluginBase<Entity>, IPlugin
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="SaveCheckboxSet" /> class.
    /// </summary>
    public SaveCheckboxSet()
      : base(typeof(SaveCheckboxSet))
    {
      this.RegisteredPluginSteps.Add(new PluginStepBase
      {
        Stage = Stage.PreValidate,
        Mode = Mode.Synchronous,
        MessageName = MessageName.Create,
        Handler = this.PrepareRelationsUpdate
      });

      this.RegisteredPluginSteps.Add(new PluginStepBase
      {
        Stage = Stage.PostOperation,
        Mode = Mode.Synchronous,
        MessageName = MessageName.Create,
        Handler = this.ProcessRelationsUpdate
      });

      this.RegisteredPluginSteps.Add(new PluginStepBase
      {
        Stage = Stage.PreValidate,
        Mode = Mode.Synchronous,
        MessageName = MessageName.Update,
        Handler = this.PrepareRelationsUpdate
      });

      this.RegisteredPluginSteps.Add(new PluginStepBase
      {
        Stage = Stage.PostOperation,
        Mode = Mode.Synchronous,
        MessageName = MessageName.Update,
        Handler = this.ProcessRelationsUpdate
      });
    }

    /// <summary>
    /// Prepares the relations update.
    /// </summary>
    /// <param name="localContext">The local context.</param>
    private void PrepareRelationsUpdate(LocalPluginContext localContext)
    {
      var manager = new Manager(localContext);
      manager.PrepareRelationsUpdate();
    }

    /// <summary>
    /// Processes the relations update.
    /// </summary>
    /// <param name="localContext">The local context.</param>
    private void ProcessRelationsUpdate(LocalPluginContext localContext)
    {
      var manager = new Manager(localContext);
      manager.UpdateRelations();
    }
  }
}
